package com.chad.baserecyclerviewadapterhelper;

import android.animation.ValueAnimator;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.chad.baserecyclerviewadapterhelper.base.BaseActivity;
import com.chad.baserecyclerviewadapterhelper.util.ToastUtils;
import com.chad.library.adapter.base.OffsetDecoration;
import com.chad.library.adapter.base.TimeLineItemDraggableAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.TimeLineViewHolder;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.chad.library.adapter.base.listener.OnItemSwipeListener;

import java.util.ArrayList;
import java.util.List;

/**
 * https://github.com/CymChad/BaseRecyclerViewAdapterHelper
 */
public class ItemDragAndSwipeUseActivity extends BaseActivity {
    private static final String TAG = ItemDragAndSwipeUseActivity.class.getSimpleName();
    private RecyclerView mRecyclerView;
    private List<String> mData;
    private TimeLineItemDraggableAdapter mAdapter;
    private ItemTouchHelper mItemTouchHelper;
    private ItemDragAndSwipeCallback mItemDragAndSwipeCallback;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item_touch_use);
        setBackBtn();
        setTitle("ItemDrag  And Swipe");
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));

        Point size = new Point();

        getWindowManager().getDefaultDisplay().getSize(size);

        final OffsetDecoration offsetDecoration = new OffsetDecoration(size.x / 2, size.x / 2);
//        mRecyclerView.addItemDecoration(offsetDecoration);


        mData = generateData(15);
        OnItemDragListener listener = new OnItemDragListener() {
            @Override
            public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {
                Log.d(TAG, "drag start");
                mAdapter.onDragStart();

                final TimeLineViewHolder holder = ((TimeLineViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.RED);
                mAdapter.onDragStart();

                offsetDecoration.setNeedOffset(false);

                for (int i = 0; i < mRecyclerView.getChildCount(); i++) {

                    View child = mRecyclerView.getChildAt(i);

                    Log.e(TAG, "child view " + i + " [left=" + child.getLeft() + ", right=" + child.getRight() + "]");

                }

                startRecyclerViewScaleAnimator(holder);

            }

            @Override
            public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {
                Log.d(TAG, "move from: " + source.getAdapterPosition() + " to: " + target.getAdapterPosition());
            }

            @Override
            public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {
                Log.d(TAG, "drag end");
                offsetDecoration.setNeedOffset(true);
//                TimeLineViewHolder holder = ((TimeLineViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.BLACK);
                mAdapter.onDragEnd();
                mAdapter.notifyDataSetChanged();


            }
        };
        final Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setTextSize(20);
        paint.setColor(Color.BLACK);
        OnItemSwipeListener onItemSwipeListener = new OnItemSwipeListener() {
            @Override
            public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {
                Log.d(TAG, "view swiped start: " + pos);
                TimeLineViewHolder holder = ((TimeLineViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.WHITE);
            }

            @Override
            public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {
                Log.d(TAG, "View reset: " + pos);
                TimeLineViewHolder holder = ((TimeLineViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.BLACK);
            }

            @Override
            public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {
                Log.d(TAG, "View Swiped: " + pos);
            }

            @Override
            public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {
                canvas.drawColor(ContextCompat.getColor(ItemDragAndSwipeUseActivity.this, R.color.color_light_blue));
//                canvas.drawText("Just some text", 0, 40, paint);
            }
        };

        mAdapter = new TimeLineItemDraggableAdapter(ItemDragAndSwipeUseActivity.this, mData);
        mItemDragAndSwipeCallback = new ItemDragAndSwipeCallback(mAdapter);
        mItemTouchHelper = new ItemTouchHelper(mItemDragAndSwipeCallback);
        mItemTouchHelper.attachToRecyclerView(mRecyclerView);

        mItemDragAndSwipeCallback.setSwipeMoveFlags(ItemTouchHelper.UP | ItemTouchHelper.DOWN);
        mAdapter.enableSwipeItem();
        mAdapter.setOnItemSwipeListener(onItemSwipeListener);
        mAdapter.enableDragItem(mItemTouchHelper);
        mAdapter.setOnItemDragListener(listener);

        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ToastUtils.showShortToast("点击了" + position);
            }
        });
    }

    private void startRecyclerViewScaleAnimator(final RecyclerView.ViewHolder viewHolder) {

        final int targetWidth = getResources().getDimensionPixelSize(R.dimen.width_dragging);
        int left = 0;

        for (int i = 0; i < mRecyclerView.getChildCount(); i++) {

            View child = mRecyclerView.getChildAt(i);

            if (viewHolder.itemView == child) {
                left = viewHolder.itemView.getLeft();
                break;
            }
        }

        ValueAnimator objectAnimator = ValueAnimator.ofFloat(0, 1);

        final int finalLeft = left;
        objectAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {

                float factor = (float) animation.getAnimatedValue();

                int currentChildCount = mRecyclerView.getChildCount();

                int scrollX = 0;


                for (int i = 0; i < currentChildCount; i++) {



                    View child = mRecyclerView.getChildAt(i);

                    if (mRecyclerView.getChildAdapterPosition(child) == 0 || mRecyclerView.getChildAdapterPosition(child) == mAdapter.getItemCount() - 1){
                        continue;
                    }

                    if (viewHolder.itemView == child) {
                        if (i > 0) {
                            scrollX = mRecyclerView.getChildAt(i - 1).getRight() - finalLeft;
                        }
                    }

                    if (child.getLayoutParams() != null) {
                        child.getLayoutParams().width = (int) (targetWidth - (factor - 1) * (child.getWidth() - targetWidth));
                        child.requestLayout();

                    }


                }


                mRecyclerView.scrollBy(scrollX, 0);


            }
        });

        objectAnimator.setDuration(300);
        objectAnimator.start();

    }


    private List<String> generateData(int size) {
        ArrayList<String> data = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            data.add("V " + i);
        }
        return data;
    }


}
